package com.atguigu.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.atguigu.base.BaseController;
import com.atguigu.entity.Admin;
import com.atguigu.entity.HouseBroker;
import com.atguigu.service.AdminService;
import com.atguigu.service.HouseBrokerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

/**
 * @author tangsy
 * @Description TODO
 * @date 2022/9/19 19:22
 * @Version 1.0
 */
@Controller
@RequestMapping("houseBroker")
@SuppressWarnings({"unchecked", "rawtypes"})
public class HouseBrokerController extends BaseController {

    @Reference
    private AdminService adminService;

    @Reference
    private HouseBrokerService houseBrokerService;

    @PreAuthorize("hasAuthority('house.editBroker')")
    @RequestMapping("create")
    public String create(Model model, @RequestParam("houseId") Long houseId){

        List<Admin> adminList = adminService.findAll();
        model.addAttribute("adminList",adminList);
        model.addAttribute("houseId",houseId);
        return "houseBroker/create";

    }

    @PreAuthorize("hasAuthority('house.editBroker')")
    @RequestMapping("save")
    public String save(HouseBroker houseBroker){

        Admin admin = adminService.getById(houseBroker.getBrokerId());
        houseBroker.setBrokerName(admin.getName());
        houseBroker.setBrokerHeadUrl(admin.getHeadUrl());
        houseBrokerService.insert(houseBroker);
        return "common/successPage";

    }

    @PreAuthorize("hasAuthority('house.editBroker')")
    @RequestMapping("edit/{id}")
    public String edit(@PathVariable("id") Long id,Model model){

        HouseBroker houseBroker = houseBrokerService.getById(id);
        List<Admin> adminList = adminService.findAll();
        model.addAttribute("adminList",adminList);
        model.addAttribute("houseBroker",houseBroker);
        return "houseBroker/edit";

    }

    @PreAuthorize("hasAuthority('house.editBroker')")
    @RequestMapping("update")
    public String update(HouseBroker houseBroker){

        Admin admin = adminService.getById(houseBroker.getBrokerId());
        houseBroker.setBrokerName(admin.getName());
        houseBroker.setBrokerHeadUrl(admin.getHeadUrl());
        houseBrokerService.update(houseBroker);
        return "common/successPage";

    }

    @PreAuthorize("hasAuthority('house.editBroker')")
    @RequestMapping("delete/{houseId}/{id}")
    public String delete(@PathVariable Long houseId, @PathVariable Long id){

        houseBrokerService.delete(id);
        return "redirect:/house/" + houseId;

    }

}
